<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\UserJob as UserJobModel;
use app\user\model\UserGroup as UserGroupModel;
use app\mill\model\Give as GiveModel;
use think\Db;

/**
 * 角色工位控制器
 * @package app\admin\controller
 */
class Job extends Admin
{
    /**
     * 工位列表页
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('admin_user_job')
            ->alias('j')
            ->field('j.*,g.name as group_name')
            ->join('admin_user_group g','g.id=j.group')
            ->where($map)
            ->order('j.id')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工位管理') // 页面标题
            ->setTableName('admin_user_job') // 设置表名
            ->setSearch(['j.name' => '工位名称', 'j.id' => 'ID']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['name', '工位名称'],
                ['group_name', '所属部门'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->addRightButton('archivesPrint',['title' => '工位码','href' => url('jobPrint',['id' => '__id__']),'class'=>'btn btn-primary disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = input();
            if (empty($data['name'])) $this->error('请输入工位名称');

            $data['create_time'] = time();
            $data['update_time'] = time();
            if (UserJobModel::create($data)) {
                $this->success('操作成功', url('index'));
            }
            $this->error('操作失败');
        }


        //部门列表
        $group_ids = implode(',',array_keys(GiveModel::$role));
        $group_list = UserGroupModel::where([['status','=',1],['id','in',$group_ids]])->column('id,name');
        unset($group_list[9]);
        return ZBuilder::make('form')
            ->addFormItems([ // 批量添加表单项
                ['text:12||||must', 'name', '工位名称[:请输入工位名称]'],
                ['select:12||||must', 'group', '部门', '必填', $group_list,],
            ])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 角色id
     * @return mixed
     */
    public function edit($id=null)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if(empty($data['name'])) $this->error('请输入工位名称');

            // 更新数据
            if (UserJobModel::update($data)) {
                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }

        $id = input('param.id');

        // 获取数据
        $info = UserJobModel::find($id);

        //部门列表
        $group_ids = implode(',',array_keys(GiveModel::$role));
        $group_list = UserGroupModel::where([['status','=',1],['id','in',$group_ids]])->column('id,name');
        unset($group_list[9]);
        return ZBuilder::make('form')
            ->setPageTitle('编辑')
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['text:12||||must', 'name', '工位名称[:请输入工位名称]'],
                ['select:12||||must', 'group', '部门', '必填', $group_list,],
            ])
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 删除角色
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用角色
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用角色
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置角色状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        foreach ($ids as $id) {

            switch ($type) {
                case 'enable':
                    if (false === UserJobModel::where('id', $id)->setField('status', 1)) {
                        $this->error('启用失败，工位ID：'.$id);
                    }
                    break;
                case 'disable':
                    if (false === UserJobModel::where('id', $id)->setField('status', 0)) {
                        $this->error('禁用失败，工位ID：'.$id);
                    }
                    break;
                case 'delete':

                    if (false === UserJobModel::where('id', 'in', $id)->delete()) {
                        $this->error('删除失败，工位ID：'.$id);
                    }
                    break;
                default:
                    $this->error('非法操作');
            }

            action_log('role_'.$type, 'admin_role', $id, UID);
        }

        $this->success('操作成功');
    }

    /**
     * 打印工位码
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function jobPrint(){

        //打印单个条形码
        $id = input('id');
        //批量打印条形码
        $ids = input('ids');

        if(!empty($ids))$where = [['id','in',$ids]];
        else $where = [['id','=',$id]];

        $list = Db::name('admin_user_job')
            ->where($where)
            ->order('id asc')
            ->select();

        $html = '<html><head></head><body style="margin: 0;margin-left: 3px;">';

        if(!empty($list)){
            foreach ($list as $k=>$v){

                $barcode = '<img style="width: 20mm" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/onload.gif" class="barcode" data-val="'.$v['id'].'">';
                $qrcode = '<div style="width: 120px;height: 120px;" class="qrcode" data-val="job'.$v['id'].'"></div>';
                $margin = 'margin-bottom: 35px;';
                $width = '73mm';
                $height = '49mm';
                $html .= '<table border="1" style="border-collapse: collapse;width: '.$width.';height: '.$height.';'.$margin.'">
<tbody>
<tr style="height: 20px"><td colspan="" style="font-size: 24px;font-weight: 900;line-height: 25px;text-align: center;display: flex;border: unset;align-items: center;justify-content: center;height: 98%;width: 99%;">'.$qrcode.'<br><div style="width: 24px;margin-left: 20px;">'.$v['name'].'</div></td></tr>
</tbody>
</table>';
            }
        }
        if($html){
            $html .= '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script><script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script><script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jquery.qrcode.min.js?v=20180327"></script><script type="text/javascript">
                $(function(){
                
                    $(".qrcode").each(function(i){
                        var val = $(this).data("val");
                        
                        //$(this).JsBarcode(val,{height:61,margin:5,displayValue:false});
                        $(this).qrcode({
                            text: ""+val+"",
                            width: 120,
                            height: 120,
                            //src: "path/to/your/logo.png" // Logo图片路径
                        });
                        
                        
                    });
                    //调用打印功能
                    window.print();
                    
                });
            </script>';
        }

        $html .= '</body></html>';

        echo $html;exit;

    }

}
